import {
  deleteUserChannels,
  getChannels,
  getUserChannels,
  patchUserChannels,
  TChannels
} from '@/api'
import { getStorage, hasStorage, setStorage } from '@/utils/loaclStorage'
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
import { TOKEN_KEY } from './login'
export const CHANNELS_KEY = 'channels'

// 获取用户频道
export const getUserChannelsAction = createAsyncThunk(
  'home/userChannels',
  async () => {
    try {
      // 判断token
      if (hasStorage(TOKEN_KEY)) {
        const res = await getUserChannels()
        setStorage(CHANNELS_KEY, res.data.data.channels)
        return res.data.data.channels
      } else {
        // 拿缓存
        const channelsList = getStorage(CHANNELS_KEY)
        if (channelsList !== null) {
          return channelsList
        } else {
          // 继续请求
          const res = await getUserChannels()
          // 存缓存
          setStorage(CHANNELS_KEY, res.data.data.channels)
          return res.data.data.channels
        }
      }
    } catch (error) {}
  }
)

// 获取所有频道
export const getChannelsAction = createAsyncThunk('home/Channels', async () => {
  try {
    const res = await getChannels()
    return res.data.data.channels
  } catch (error) {}
})

// 添加频道
export const patchUserChannelsAction = createAsyncThunk(
  'home/patchUserChannels',
  async (channels: TChannels[]) => {
    try {
      // 最终返回值
      let payload : TChannels[]
      // 登陆
      if (hasStorage(TOKEN_KEY)) {
        await patchUserChannels(channels)
        const res = await getUserChannels()
        payload = res.data.data.channels
      } else {
        // 没登陆
        let channelsList = getStorage<Array<TChannels>>(CHANNELS_KEY)
        // 为数组
        if (channelsList) {
          channelsList.push(...channels)
        } else {
          // 为null时
          channelsList = [...channels]
        }
        payload = channelsList
      }
      // 存缓存
      setStorage(CHANNELS_KEY, payload)
      return payload
    } catch (error) {}
  }
)

// 删除指定频道
export const deleteUserChannelsAction = createAsyncThunk(
  'home/deleteUserChannels',
  async (channel: TChannels) => {
    try {
      // 最终返回值
      let payload : TChannels[]
      // 登陆
      if(hasStorage(TOKEN_KEY)){
        await deleteUserChannels(channel.id)
        const res = await getUserChannels()
        payload = res.data.data.channels
      }else{
        // 没登陆
        const channelsList = getStorage<Array<TChannels>>(CHANNELS_KEY)
        payload= channelsList.filter(c=>channel.id !== c.id)
      }
      // 存缓存
      setStorage(CHANNELS_KEY, payload)
      return payload
    } catch (error) {}
  }
)

export interface IHomeState {
  // 用户频道
  channels: TChannels[]
  // 全部频道
  allChannels: TChannels[]
  // 设置高亮
  active: number
}

const initialState: IHomeState = {
  channels: [],
  allChannels: [],
  active: 0
}
export const homeSlice = createSlice({
  name: 'home',
  initialState,
  reducers: {
    activeAction (state, action: PayloadAction<number>) {
      state.active = action.payload
    }
  },
  extraReducers: {
    // 获取用户频道【成功】
    [getUserChannelsAction.fulfilled.type]: (
      state,
      action: PayloadAction<TChannels[]>
    ) => {
      state.channels = action.payload
    },
    // 获取全部频道【成功】
    [getChannelsAction.fulfilled.type]: (
      state,
      action: PayloadAction<TChannels[]>
    ) => {
      state.allChannels = action.payload
    },
    // 添加频道【成功】
    [patchUserChannelsAction.fulfilled.type]: (
      state,
      action: PayloadAction<TChannels[]>
    ) => {
      state.channels = action.payload
    },
    // 删除指定频道【成功】
    [deleteUserChannelsAction.fulfilled.type]:(state,action:PayloadAction<TChannels[]>)=>{
      state.channels = action.payload
    }
  }
})
// Action creators are generated for each case reducer function
export const { activeAction } = homeSlice.actions

export default homeSlice.reducer
